package com.qyhl.webtv.module_microvideo.shortvideo.play.comment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoCommentBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoNewCommentBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import razerdp.basepopup.BasePopupWindow;

public class QXShortVideoCommentPopupWindow extends BasePopupWindow implements ShortVideoCommentContract.ShortVideoCommentView {
    private RecyclerView recyclerView;
    private LoadingLayout loadMask;
    private SmartRefreshLayout refreshLayout;
    private TextView sendBtn;
    private EditText content;
    private View popupView;
    private ImageView closeBtn;

    private CommonAdapter commonAdapter;

    private List<ShortVideoCommentBean> mDataList = new ArrayList<>();

    private int page = 1;

    private String workId;

    private ShortVideoCommentPresenter mPresenter;

    private Activity mContext;

    private String userName;

    private String userNickName;

    private String mContent;

    private String userLogo;

    public QXShortVideoCommentPopupWindow(Activity context, String id) {
        super(context);
        mPresenter = new ShortVideoCommentPresenter(this);
        workId = id;
        mContext = context;
        bindEvent();
        initView();
        setListener();
    }

    @Override
    protected Animation initShowAnimation() {
        return getDefaultScaleAnimation();
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.close_btn);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreatePopupView() {
        return popupView = LayoutInflater.from(getContext()).inflate(R.layout.micro_popup_short_video_comment_qx, null);
    }

    @Override
    public View initAnimaView() {
        return findViewById(R.id.popup_anima);
    }

    private void bindEvent() {
        recyclerView = popupView.findViewById(R.id.recycle_view);
        loadMask = popupView.findViewById(R.id.load_mask);
        refreshLayout = popupView.findViewById(R.id.refresh);
        sendBtn = popupView.findViewById(R.id.send_btn);
        content = popupView.findViewById(R.id.content);
        closeBtn = popupView.findViewById(R.id.close_btn);
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setRefreshHeader(new MaterialHeader(mContext));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<ShortVideoCommentBean>(mContext, R.layout.micro_item_short_video_comment_qx, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShortVideoCommentBean bean, int position) {
                holder.setText(R.id.nickName, bean.getUserNickName());
                holder.setText(R.id.content, bean.getContent());
                holder.setText(R.id.date, DateUtils.mTranslateDate(bean.getCreateDate()));

                RoundedImageView headIcon = holder.getView(R.id.head_icon);
                Glide.with(mContext)
                        .load(bean.getUserLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headIcon);
            }
        });

        page = 1;
        mPresenter.getComment(workId, page + "");
    }

    private void setListener() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            page = 1;
            mPresenter.getComment(workId, page + "");
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getComment(workId, page + "");
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> mPresenter.getComment(workId, page + ""));

        closeBtn.setOnClickListener(v -> {
            hideKeyboard(mContext, content);
            dismiss();
        });

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBtn.setEnabled(false);
                if (StringUtils.isNotEmpty(content.getText().toString()) && StringUtils.isNotEmpty(content.getText().toString().trim())) {

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                userName = (String) CommonUtils.getInstance().getUserName();
                                mContent = content.getText().toString();
                                userLogo = CommonUtils.getInstance().getUserLogo();
                                userNickName = CommonUtils.getInstance().getNickName();
                                mPresenter.addComment(workId, mContent, userName);
                            } else {
                                sendBtn.setEnabled(true);
                                Toasty.normal(mContext, "尚未登录或登录已失效！").show();
                                RouterManager.routerLogin(mContext, 0);
                            }
                        }

                        @Override
                        public void error(String s) {
                            sendBtn.setEnabled(true);
                        }
                    });


                } else {
                    sendBtn.setEnabled(true);
                    Toast.makeText(mContext, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setComment(ShortVideoNewCommentBean bean, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        page++;
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(bean.getCommentList());
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setCommentError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText(msg);
            loadMask.setErrorImage(R.drawable.empty_comment);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void commentSuccess(String num, String msg) {
        sendBtn.setEnabled(true);
        loadMask.setStatus(LoadingLayout.Success);
        if (msg.equals("请耐心等待审核")) {
            Toast.makeText(mContext, "评论成功，等待审核！", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "评论成功！", Toast.LENGTH_SHORT).show();
            mDataList.add(0, new ShortVideoCommentBean(mContent, DateUtils.getCurrentTime(), userLogo, userNickName));
            commonAdapter.notifyDataSetChanged();
            BusFactory.getBus().post(new Event.refreshCommentNum(num));
        }
        content.setText("");
        mContent = "";
        content.clearFocus();
        hideKeyboard(mContext, content);

    }

    @Override
    public void commentError(String msg) {
        sendBtn.setEnabled(true);
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 隐藏软键盘
     *
     * @param context 上下文对象
     * @param view    可弹出软键盘控件
     */
    public void hideKeyboard(Context context, View view) {
        if (view == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onDismiss() {
        super.onDismiss();
        hideKeyboard(mContext, content);
    }
}
